from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from BlogAutoTest.common.Utils import BlogDriver


class BlogList:
    def __init__(self):
        self.url = "http://8.137.19.140:9090/blog_login.html"
        self.driver = BlogDriver.driver
        self.driver.get(self.url)
        self.wait = WebDriverWait(self.driver, 10)  # 全局显式等待，超时10秒

    # 测试首页登录状态下
    def BlogListLogin(self):
        self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,"#username"))).send_keys("zhangsan")
        self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,"#password"))).send_keys("123456")
        self.wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#submit"))).click()

        try:
            # 检查标题
            self.wait.until(
                EC.presence_of_element_located((By.CSS_SELECTOR, "body > div.container > div.right > div:nth-child(1) > div.title"))
            )
            # 检查头像
            self.wait.until(
                EC.presence_of_element_located((By.CSS_SELECTOR, "body > div.container > div.left > div > img"))
            )
            # 点击“查看全文”
            self.wait.until(
                EC.element_to_be_clickable((By.CSS_SELECTOR, "body > div.container > div.right > div:nth-child(1) > a"))
            ).click()
            # 验证是否进入详情页（检查文章标题）
            self.wait.until(
                EC.presence_of_element_located((By.CSS_SELECTOR, "body > div.container > div.right > div > div.title"))
            )
            self.driver.back()

            # 点击“写博客”按钮
            self.wait.until(
                EC.element_to_be_clickable((By.CSS_SELECTOR, "body > div.nav > a:nth-child(5)"))
            ).click()
            # 验证是否进入写博客页面（检查标题输入框）
            self.wait.until(
                EC.presence_of_element_located((By.CSS_SELECTOR, "#title"))
            )
            self.driver.back()

            # 点击“注销”按钮
            self.wait.until(
                EC.element_to_be_clickable((By.CSS_SELECTOR, "body > div.nav > a:nth-child(6)"))
            ).click()
            # 验证是否返回登录页（检查登录输入框）
            self.wait.until(
                EC.presence_of_element_located((By.CSS_SELECTOR, "#username"))
            )

        except Exception as e:
            print("BlogListLogin 执行失败:", e)
            BlogDriver.getScreeShot()  # 失败时截图
            raise

    # 测试首页未登录状态下
    def BlogListUnlogin(self):
        try:
            # 点击“主页”按钮
            self.wait.until(
                EC.element_to_be_clickable((By.CSS_SELECTOR, "body > div.nav > a:nth-child(4)"))
            ).click()
            # 截图保存结果
            BlogDriver.getScreeShot()
        except Exception as e:
            print("BlogListUnlogin 执行失败:", e)
            BlogDriver.getScreeShot()
            raise